<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button
            type="primary"
            size="small"
            @click="hAdd( '0' , 1) "
          >添加权限</el-button>
        </div>
        <!-- row-key="id" row-key 表格可以展示树形数据展示  id(唯一值就行不固定)  -->
        <el-table row-key="id" :data="list" border>
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template #default="{row}">
              <el-button
                v-if="row.type === 1 && row.pid==='0' "
                type="text"
                @click="hAdd(row.id , 2)"
              >添加</el-button>
              <el-button type="text" @click="hPut(row)">编辑</el-button>
              <el-button type="text" @click="del(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 新增权限的弹层 -->
      <el-dialog
        :title="isEdit ?'编辑' :'添加' "
        :destroy-on-close="true"
        :visible.sync="showDialog"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        @close="reset"
      >
        <!-- 表单内容 -->
        <el-form ref="formRef" :rules="rules" :model="formData" label-width="100px">
          <el-form-item label="权限名称" prop="name">
            <el-input v-model="formData.name" />
          </el-form-item>
          <el-form-item label="权限标识" prop="code">
            <el-input v-model="formData.code" />
          </el-form-item>
          <el-form-item label="权限描述">
            <el-input v-model="formData.description" />
          </el-form-item>
          <el-form-item label="权限启用">
            <el-switch
              v-model="formData.enVisible"
              active-text="启用"
              active-value="1"
              inactive-text="不启用"
              inactive-value="0"
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <div style="text-align: right;">
            <el-button @click="showDialog = false">取消</el-button>
            <el-button type="primary" @click="hScumit">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getPermissionList, addPermission, delPermission, updatePermission } from '@/api/permissions'
// 平铺数据转换 树形数据
import { transDataToTreeData } from '@/utils/index'
export default {
  data() {
    // 自定义校验code
    const validCode = (rule, value, callback) => {
      // 获取所有code 放入对象中
      let isCode = this.treeList.map(item => item.code)
      // console.log('isCode', isCode)
      if (this.isEdit === true) {
        // 处于编辑状态 吧自己去除掉 在做判断
        isCode = this.treeList.filter(item => item.id !== this.formData.id).map(item => item.code)
        // console.log('isCode修改的', isCode)
      }

      if (isCode.includes(value)) {
        callback(new Error(`当前添加的:${value}重复,请重新输入`))
      } else {
        callback()
      }
    }
    // 自定义校验name
    const validName = (rule, value, callback) => {
      // 获取所有code 放入对象中
      let isName = this.treeList.filter(item => item.pid === this.formData.pid).map(item => item.name)
      console.log('添加', isName)
      if (this.isEdit) {
        // 编辑状态
        // 先拿到与自己同级的元素  判断同级name不可重复, 去除自己 在取name     注意编辑的时候拿的就是自己的id
        const pid = this.treeList.find(item => item.id === this.formData.id).pid
        console.log('pid', pid)
        isName = this.treeList.filter(item => item.pid === pid).filter(item => item.id !== this.formData.id).map(item => item.name)

        // console.log('编辑状态', pid)
        console.log('编辑', isName)
      }

      if (isName.includes(value.trim())) {
        callback(new Error(`当前已拥有:${value}名称,不可以重复添加`))
      } else {
        callback()
      }
    }
    return {
      list: [], // 保存权限列表数据
      showDialog: false,
      isEdit: false,
      // 弹层数据
      formData: {
        name: '',
        code: '',
        description: '',
        enVisible: 0, // 控制启用不起用按钮
        type: null,
        pid: null
      },
      treeList: [], // 保存数据做表单校验使用
      rules: {
        name: [
          { required: true, message: '请输入权限名称', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入权限标识', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadPermissionList()
  },
  methods: {
    // 手动表单数据重置
    reset() {
      this.formData = {
        name: '',
        code: '',
        description: '',
        enVisible: 0, // 控制启用不起用按钮
        type: null,
        pid: '0'
      }
      this.showDialog = false
    },
    // 点击了确定
    hScumit() {
      // 兜底校验
      // 三元判断    ? 编辑状态执行           : 添加状态执行
      this.isEdit ? this.putPermission() : this.savePermission()
    },
    // 新增权限
    async savePermission() {
      try {
        const res = await addPermission(this.formData)
        console.log('addPermission', res)
        // 保存数据
        this.loadPermissionList()
        this.showDialog = false
        this.$message.success(res.message)
      } catch (err) {
        console.log('addPermission', err)
      }
    },
    // 修改权限
    async putPermission() {
      try {
        const res = await updatePermission(this.formData)
        console.log('updatePermission', res)
        // 保存数据
        if (res.code !== 10000) return
        this.loadPermissionList()
        this.showDialog = false
        this.$message.success(res.message)
      } catch (err) {
        console.log('updatePermission', err)
      }
    },
    // 点击了添加权限
    hAdd(pid, type) {
      // console.log(pid)
      this.isEdit = false // 修改表单状态
      this.formData.pid = pid
      this.formData.type = type
      this.showDialog = true
    },
    // 点击了编辑
    hPut(row) {
      this.isEdit = true // 修改表单状态
      this.showDialog = true
      //  {...row} 这个地方是数据 浅拷贝
      this.formData = { ...row }
    },
    // 获取权限
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        // console.log('getPermissionList', res)
        // 保存数据
        this.treeList = res.data.map(item => {
          return { id: item.id, pid: item.pid, name: item.name, type: item.type, code: item.code }
        })
        this.list = transDataToTreeData(res.data)
      } catch (err) {
        console.log('getPermissionList', err)
      }
    },
    // 点击了删除
    del(id) {
      this.$confirm('你点击了删除,是否继续?', '提示').then(async() => {
        try {
          const res = await delPermission(id)
          console.log('delPermission', res)
          // 保存数据
          if (res.code !== 10000) return
          this.$message.success(res.message)
          this.loadPermissionList()
        } catch (err) {
          console.log('delPermission', err)
        }
      }).catch(err => console.log(err))
    }

  }
}
</script>
